package com.sinosoft.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sinosoft.attachment.Attachment;
import com.sinosoft.attachment.AttachmentManager;
import com.sinosoft.base.BaseFormController;
import com.sinosoft.base.Constants;
import com.sinosoft.report.Item;
import com.sinosoft.report.ReportComments;
import com.sinosoft.util.CheckEmpty;
import com.sinosoft.util.DisplayGetPage;
import com.sinosoft.util.PropertiesUtil;

@Controller
public class AttachmentController extends BaseFormController {

	private AttachmentManager amManager;

	@Autowired
	public void setAmManager(AttachmentManager amm) {
		this.amManager = amm;
	}

	/**
	 * 资源管理列表
	 * 
	 * @param atch
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/fileDownload.html")
	public String getAllAttachment(Attachment atch, Model model,
			HttpServletRequest request, HttpServletResponse response) {
		List<Attachment> list = null;
		// 获取session
		HttpSession session = request.getSession(true);
		// 判断是否是管理页面跳转过来
		String returntype = request.getParameter("returntype");
		if (!CheckEmpty.isEmpty(returntype)) {
			if (returntype.equals("false")) {
				atch = (Attachment) session.getAttribute("Attachment");
			}
		}
		if (null != atch) {
			session.setAttribute("Attachment", atch);
		}
		String page = DisplayGetPage.getPageParamName("file", request);// 第几页
		if (page == null) {
			list = amManager.getAttachments(atch, 0, Constants.pagesize);
		} else {
			list = amManager.getAttachments(atch, (Integer.parseInt(page) - 1)
					* Constants.pagesize, Constants.pagesize);
		}
		int ttachmentNum = amManager.getAttachmentNum(atch);
		if (null != list && list.size() > 0) {
			model.addAttribute("filelistresult", true);
		} else {
			model.addAttribute("filelistresult", false);
		}
		// 获取display名称
		String pagename = DisplayGetPage.getPageName("file", request);
		model.addAttribute("pagename", pagename);
		model.addAttribute("resultSize", ttachmentNum);
		model.addAttribute("pagesize", Constants.pagesize);
		model.addAttribute("authoriyid", atch);
		// 判断删除或修改结果 并在页面提示
		String result = request.getParameter("resultstr");
		if (!CheckEmpty.isEmpty(result)) {
			if (result.equals("1")) {
				result = PropertiesUtil.getPropertiesValue(
						"authoriy.update.seccuss", request)[0];
			} else if (result.equals("2")) {
				result = PropertiesUtil.getPropertiesValue(
						"authoriy.update.error", request)[0];
			} else if (result.equals("3")) {
				result = PropertiesUtil.getPropertiesValue(
						"authoriy.delete.seccuss", request)[0];
			} else if (result.equals("4")) {
				result = PropertiesUtil.getPropertiesValue(
						"authoriy.delete.error", request)[0];
			}
		}
		// 资源类型
		String[] attachmenttype = PropertiesUtil.getPropertiesValue("authoriy.type.list",
				request);
		List<Item> attachmenttypelist = ReportComments.getList(attachmenttype);
		model.addAttribute("attachmenttypelist", attachmenttypelist);
		// 是否发布
		String[] isrelease = PropertiesUtil.getPropertiesValue("authoriy.isrelease.list",
				request);
		List<Item> isreleaselist = ReportComments.getList(isrelease);
		model.addAttribute("isreleaselist", isreleaselist);
		
		// 判断下载结果并以弹框提示！
		String message = checkDownloadResult(request);
		model.addAttribute("downlaodresult", message);
		model.addAttribute("resultstr", result);
		double pagesize = Constants.pagesize;
		model
				.addAttribute("displayallpage", Math.ceil(ttachmentNum
						/ pagesize));
		model.addAttribute("thispage", Integer.parseInt(page));
		model.addAttribute("downLoadList", list);
		return "attachment/fileDownload";
	}

	/**
	 * 首页查询列表
	 * 
	 * @param atch
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/loginquerylist.html")
	public ModelAndView loginQueryList(Attachment atch, Model model,
			HttpServletRequest request, HttpServletResponse response) {
		List<Attachment> list = null;
		String attachmentType = request.getParameter("atype");
		if (!CheckEmpty.isEmpty(attachmentType)) {
			atch.setFileType(Long.parseLong(attachmentType));
		}
		atch.setIsRelease(Long.parseLong(Constants.ATTACHMENT_ISRELEASE_YES));
		// 获取session
		HttpSession session = request.getSession(true);
		// 判断是否是管理页面跳转过来
		String returntype = request.getParameter("returntype");
		if (!CheckEmpty.isEmpty(returntype)) {
			if (returntype.equals("false")) {
				atch = (Attachment) session.getAttribute("Attachment");
			}
		}
		if (null != atch) {
			session.setAttribute("Attachment", atch);
		}
		String page = DisplayGetPage.getPageParamName("file", request);// 第几页
		if (page == null) {
			list = amManager.getAttachments(atch, 0, Constants.pagesize);
		} else {
			list = amManager.getAttachments(atch, (Integer.parseInt(page) - 1)
					* Constants.pagesize, Constants.pagesize);
		}
		int ttachmentNum = amManager.getAttachmentNum(atch);
		if (null != list && list.size() > 0) {
			model.addAttribute("filelistresult", true);
		} else {
			model.addAttribute("filelistresult", false);
		}
		// 资源类型
		String[] attachmenttype = PropertiesUtil.getPropertiesValue("authoriy.type.list",
				request);
		List<Item> attachmenttypelist = ReportComments.getList(attachmenttype);
		model.addAttribute("attachmenttypelist", attachmenttypelist);
		// 判断下载结果并以弹框提示！
		String message = checkDownloadResult(request);
		// 获取display名称
		String pagename = DisplayGetPage.getPageName("file", request);
		model.addAttribute("pagename", pagename);
		model.addAttribute("downlaodresult", message);
		model.addAttribute("resultSize", ttachmentNum);
		model.addAttribute("pagesize", Constants.pagesize);
		model.addAttribute("authoriyid", atch);
		double pagesize = Constants.pagesize;
		model
				.addAttribute("displayallpage", Math.ceil(ttachmentNum
						/ pagesize));
		model.addAttribute("thispage", Integer.parseInt(page));
		return new ModelAndView("attachment/loginquerylist", "downLoadList",
				list);
	}

	/**
	 * 添加新的资源信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/fileUpload.html")
	public String addAttachment(HttpServletRequest request,
			HttpServletResponse response) {
		// 设置字符集
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String filename = request.getParameter("filename");
		String filetype = request.getParameter("filetype");
		String filepath = request.getParameter("filepath");
		String isrelease = request.getParameter("isrelease");
		String note = request.getParameter("note");
		BigDecimal filesize = BigDecimal.valueOf(Double.parseDouble(request.getParameter("filesize")));

		Attachment achment = new Attachment();
		if (!CheckEmpty.isEmpty(filetype)) {
			Long ftype = Long.parseLong(filetype);
			achment.setFileType(ftype);
		}
		if (!CheckEmpty.isEmpty(isrelease)) {
			Long release = Long.parseLong(isrelease);
			achment.setIsRelease(release);
		}
		achment.setCreateTime(new Date());
		achment.setFileName(filename);
		achment.setFilePath(filepath);
		achment.setFileSize(filesize);
		achment.setNote(note);
		PrintWriter out;
		if (null != achment) {
			achment = amManager.saveAttachment(achment);
			if (achment.getId() > 0) {
				request.setAttribute("uploadResult", true);
				String result = PropertiesUtil.getPropertiesValue(
						"authoriy.download.seccuss", request)[0];
				try {
					out = response.getWriter();
					out.print("<script type='text/javascript'>alert(\""
							+ result + "\");</script>");
				} catch (IOException e) {
					e.printStackTrace();
				}

			} else {
				String result = PropertiesUtil.getPropertiesValue(
						"authoriy.download.error", request)[0];
				try {
					out = response.getWriter();
					out.print("<script type='text/javascript'>alert(\""
							+ result + "\");</script>");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "redirect:/attachment/fileDownload.html";
	}

	/**
	 * 下载资源
	 * 
	 * @param fliepath
	 * @param name
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/download.html")
	public String downLoad(HttpServletRequest request,
			HttpServletResponse response) {
		
		String returnpath = "redirect:/attachment/fileDownload.html";
		try {
			String fliepath = request.getParameter("fpath");
			String name = request.getParameter("name");
			String pathtype = request.getParameter("pathtype");
			String pagename = request.getParameter("pagename");
			String page = request.getParameter("thispage");
			if (!CheckEmpty.isEmpty(pathtype)) {
				if (pathtype.equals("1")) {
					returnpath = "redirect:../index.html";
				} else if (pathtype.equals("2")) {
					returnpath = "redirect:/attachment/loginquerylist.html?returntype=false&"
							+ pagename + "=" + page;
				} else {
					if (!CheckEmpty.isEmpty(pagename)
							&& !CheckEmpty.isEmpty(page)) {
						returnpath = "redirect:/attachment/fileDownload.html?returntype=false&"
								+ pagename + "=" + page;
					} else {
						returnpath = "redirect:/attachment/fileDownload.html";
					}
				}
			}

			// web绝对路径
			String filepath = request.getSession().getServletContext()
					.getRealPath(fliepath);
			File f = new File(filepath);
			if (f.exists()) {
				// 设置为下载application/x-download
				response.setContentType("application/x-download");
				// 即将下载的文件在服务器上的绝对路径
				String filenamedownload = filepath;
				// 下载文件时显示的文件保存名称
				String filenamedisplay = name
						+ fliepath.substring(fliepath.lastIndexOf("."),
								fliepath.length());
				// 中文编码转换
				try {
					filenamedisplay = URLEncoder.encode(filenamedisplay,
							"UTF-8");
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				response.addHeader("Content-Disposition",
						"attachment;filename=" + filenamedisplay);
				try {
					OutputStream os = response.getOutputStream();
					FileInputStream fis = new java.io.FileInputStream(
							filenamedownload);
					byte[] b = new byte[1024];
					int i = 0;
					while ((i = fis.read(b)) > 0) {
						os.write(b, 0, i);
					}
					fis.close();
					os.flush();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			} else {
				request.getSession().setAttribute("downlaodresult", "2");
				return returnpath;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	

	/**
	 * 跳转到上传资源页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("filemanage/queryuploadfile.html")
	public String queryUploadAttachment(HttpServletRequest request,
			HttpServletResponse response) {
		return "attachment/fileUpload";
	}

	/***
	 * 欲修改查询
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/queryupdatefile.html")
	public String queryUpdateAttachment(Model model,
			HttpServletRequest request, HttpServletResponse response) {
		String achid = request.getParameter("achid");
		if (!CheckEmpty.isEmpty(achid)) {
			Attachment ach = amManager.getAttachmentById(Long.parseLong(achid));
			model.addAttribute("fileinfo", ach);
			String thispage = request.getParameter("thispage");
			String pagename = request.getParameter("pagename");
			model.addAttribute("thispage", thispage);
			model.addAttribute("pagename", pagename);
			return "attachment/updatefile";
		} else {
			return null;
		}

	}

	/**
	 * 修改资源信息
	 * 
	 * @param fileinfo
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/updateattachment.html")
	public String updateAttachment(Attachment fileinfo,
			HttpServletRequest request, HttpServletResponse response) {
		String updateresult = null;
		try {
			if (fileinfo.getId() > 0) {
				Attachment ach = amManager.getAttachmentById(fileinfo.getId());
				if (null != ach) {
					ach.setFileName(fileinfo.getFileName());
					ach.setFileType(fileinfo.getFileType());
					ach.setIsRelease(fileinfo.getIsRelease());
					amManager.saveAttachment(ach);
					updateresult = "1";
				} else {
					updateresult = "2";
				}
			} else {
				updateresult = "2";
			}
		} catch (Exception e) {
			updateresult = "2";
		}
		String pagename = request.getParameter("pagename");
		String page = request.getParameter("thispage");
		if (!CheckEmpty.isEmpty(pagename) && !CheckEmpty.isEmpty(page)) {
			return "redirect:/attachment/fileDownload.html?returntype=false&resultstr="
					+ updateresult + "&" + pagename + "=" + page;
		} else {
			return "redirect:/attachment/fileDownload.html?resultstr="
					+ updateresult;
		}

	}

	/**
	 * 删除资源
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/deleteattachment.html")
	public String deleteAttachment(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "4";
		try {
			String id = request.getParameter("id");
			if (!CheckEmpty.isEmpty(id)) {
				Attachment ath = amManager
						.getAttachmentById(Long.parseLong(id));
				if (null != ath) {
					String filepath = ath.getFilePath();
					filepath = request.getSession().getServletContext()
							.getRealPath(filepath);
					try {
						File file = new File(filepath);
						if (file.exists()) {
							file.delete();
						}
						amManager.deleteAttachmentById(ath);
						result = "3";
					} catch (Exception e) {
						result = "4";
						e.printStackTrace();
					}

				} else {
					result = "4";
				}
			} else {
				result = "4";
			}
		} catch (Exception e) {
			result = "4";
		}
		String pagename = request.getParameter("pagename");
		String page = request.getParameter("thispage");
		if (!CheckEmpty.isEmpty(pagename) && !CheckEmpty.isEmpty(page)) {
			return "redirect:/attachment/fileDownload.html?returntype=false&resultstr="
					+ result + "&" + pagename + "=" + page;
		} else {
			return "redirect:/attachment/fileDownload.html?resultstr=" + result;
		}
	}

	/**
	 * 判断下载结果并以弹框提示！
	 */
	private String checkDownloadResult(HttpServletRequest request) {
		String message = null;
		if (null != request.getSession().getAttribute("downlaodresult")) {
			String downlaodresult = request.getSession().getAttribute(
					"downlaodresult").toString();
			request.getSession().removeAttribute("downlaodresult");
			if (!CheckEmpty.isEmpty(downlaodresult)) {
				if (downlaodresult.equals("1")) {
					message = PropertiesUtil.getPropertiesValue(
							"authoriy.download.success", request)[0].toString();
				} else {
					message = PropertiesUtil.getPropertiesValue(
							"authoriy.file.notiexits", request)[0].toString();
				}
			}
		}
		return message;
	}
	
	/**
	 * 根据资源id查询资源详情
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("attachment/attachmentinfo.html")
	public String searchAttachmentInfoById(Model model,
			HttpServletRequest request, HttpServletResponse response){
		try {
			String strid=request.getParameter("id");
			if(!CheckEmpty.isEmpty(strid)){
				Long id=Long.parseLong(strid);
				Attachment ach=amManager.getAttachmentById(id);
				model.addAttribute("attachment", ach);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "attachment/fileinfo";
	}
}
